package com.yifeng.repo.controller.excel.loader.task.handler;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import com.yifeng.repo.controller.excel.loader.biz.BizBaseAction;
import org.apache.poi.ss.usermodel.*;

import java.util.List;

/**
 * Created by daibing on 2023/3/31.
 */
public class ExcelWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
    private final BizBaseAction bizBaseAction;
    private CellStyle commonCellStyle;

    public ExcelWidthStyleStrategy(BizBaseAction bizBaseAction) {
        this.bizBaseAction = bizBaseAction;
    }

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList,
                                  Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        // 宽度
        writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), bizBaseAction.columnWidth(cell));

        // 样式
        cell.setCellStyle(getCellStyle(cell));
    }

    private CellStyle getCellStyle(Cell cell) {
        CellStyle cellStyle = bizBaseAction.cellStyle(cell);
        if (cellStyle != null) {
            return cellStyle;
        }
        if (commonCellStyle != null) {
            return commonCellStyle;
        }
        commonCellStyle = bizBaseAction.commonCellStyle(cell);
        if (commonCellStyle != null) {
            return commonCellStyle;
        }

        // 构造一个新的CellStyle。
        Workbook wb = cell.getSheet().getWorkbook();
        commonCellStyle = wb.createCellStyle();

        // 左对齐，垂直居中对齐
        commonCellStyle.setAlignment(HorizontalAlignment.LEFT);
        commonCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 边框线
        commonCellStyle.setBorderLeft(BorderStyle.THIN);
        commonCellStyle.setBorderRight(BorderStyle.THIN);
        commonCellStyle.setBorderBottom(BorderStyle.THIN);
        commonCellStyle.setBorderTop(BorderStyle.THIN);

        // 自动换行
        commonCellStyle.setWrapText(true);
        return commonCellStyle;
    }

}
